package com.yuan.aiagent.app;

import com.yuan.aiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Service
public class CodeApp {

    private ChatClient chatClient;

    //AI知识库问答功能
    @Resource
    private VectorStore vectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    public CodeApp(ChatModel ollamaChatModel) {
        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(ollamaChatModel)
                .defaultSystem("你是一名资深军事模拟专家，精通AFSIM脚本编写与场景搭建。" +
                        "如果用户需要AFSIM脚本代码，需要严格按照模板和模型参数编写。")
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
                )
                .build();
    }

    /**
     * 恋爱知识库问答
     * SSE 流式调用
     */
    public String doChatWithRange(String message, String chatId){
        //用户提示词重写
        String rewriteMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse response = chatClient
                .prompt()
                .user(rewriteMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new QuestionAnswerAdvisor(vectorStore))
                //.advisors(AppRagCustomAdvisorFactory.createAppRagCustomAdvisor(appvectorStore,"单身"))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        return content;
    }

    public Flux<String> doChatByStream(String message, String chatId){
        return chatClient.prompt()
                .user(chatId)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }

}
